<?php
/**
 * 自助服务接口
 * 
 * 所有金额单位一律精确到小数点后两位
 * 
*/
namespace Admin\Service;
use \Admin\Model, Admin\Service\EcontractService,Admin\Service\CustomerService,Admin\Service\SubscriberService;


class OrderApiService {
    //获取精确单位
    const CURRENCY_FIX = 2;
    const RET_ERROR = 'error';
    const RET_SUCCESS = 'success';
    const API_OK = '1000';
    const API_ERROR = '4001';
    const API_METHOD_ERROR = '4002';
    const API_PARAM_ERROR = '4003';

    //产品套餐相关
    const API_PRODUCT_NO_DATA = '2001';

    //付款信息
    const API_PAY_ERROR = '2101';
    const API_PAY_FAILED = '2102';

    //电子合同相关
    const API_ECONTRACT_PARAM_ERROR = '2201';
    const API_ECONTRACT_URL_ERROR = '2202';
    const API_ECONTRACT_CUSTOMER_ERROR = '2203';
    const API_ECONTRACT_CONTRACT_ERROR = '2204';
    const API_ECONTRACT_API_ERROR = '2205';
    const API_ECONTRACT_DETAIL_ERROR = '2206';


    //客户相关
    const API_CUSTOMER_NO_DATA = '2301';
    const API_CUSTOMER_PARAM_MISSING = '2302';
    const API_CUSTOMER_PHONE_WRONG = '2303';
    const API_CUSTOMER_CONTRACT_PARAM = '2304';
    const API_CUSTOMER_CONTRACT_TIME = '2305';
    const API_CUSTOMER_PACKAGE_WRONG = '2306';
    const API_CUSTOMER_PAY_WRONG = '2307';
    const API_CUSTOMER_USER_MISSING = '2308';  
    const API_CUSTOMER_REGISTER_FAILED = '2309';
    const API_CUSTOMER_CONTRACT_FAILED = '2310';

    //订阅用户相关
    const API_SUBSCRIBER_CREATE_ERROR = '2401';
    const API_SUBSCRIBER_UPDATE_ERROR = '2402'; 


    private $m_error = array(
        self::API_OK => '接口调用成功',
        self::API_PRODUCT_NO_DATA => '产品套餐不存在',
        self::API_PAY_ERROR => '付款信息错误',
        self::API_PAY_FAILED => '付款信息添加失败',
        self::API_ECONTRACT_PARAM_ERROR => '电子合同发起参数错误',
        self::API_ECONTRACT_URL_ERROR => '参数不完整',
        self::API_ECONTRACT_CUSTOMER_ERROR => '客户信息错误',
        self::API_ECONTRACT_CONTRACT_ERROR => '合同信息错误',
        self::API_ECONTRACT_API_ERROR   => '电子合同发起错误',
        self::API_ECONTRACT_DETAIL_ERROR => '查询合同详情失败',
        self::API_CUSTOMER_NO_DATA    => '客户信息不存在',
        self::API_CUSTOMER_PARAM_MISSING => '客户信息不完整',
        self::API_CUSTOMER_PHONE_WRONG => '电话格式错误',
        self::API_CUSTOMER_CONTRACT_PARAM => '合同参数缺失',
        self::API_CUSTOMER_CONTRACT_TIME  => '合同时间错误',
        self::API_CUSTOMER_PACKAGE_WRONG => '套餐或者企业号不存在',
        self::API_CUSTOMER_PAY_WRONG     => '付款数据错误',
        self::API_CUSTOMER_USER_MISSING => '后台员工不存在',
        self::API_CUSTOMER_REGISTER_FAILED => '客户信息注册失败',
        self::API_CUSTOMER_CONTRACT_FAILED  => '合同生成失败',
        self::API_SUBSCRIBER_CREATE_ERROR   => '订阅用户创建失败',
        self::API_SUBSCRIBER_UPDATE_ERROR   => '订阅用户更新失败',
        self::API_ERROR => '接口不存在',
        self::API_METHOD_ERROR => '接口请求方法错误',
        self::API_PARAM_ERROR => '参数错误',
    );

    private function  _E($code){
        return $code&&isset($this->m_error[$code]) ? $this->m_error[$code]:'';
    }

    public function apiError(){
        $res = array('result'=>self::RET_ERROR, 'msg'=>'','code'=>self::API_ERROR);
        $res['msg'] = $this->_E(self::API_ERROR);
        return $res;
    }

    /**
     *  统一金额数据格式
     * 
    */
    private function _uniCurrency( $money, $fix = self::CURRENCY_FIX)
    {
        if ($money){
            $money = number_format(doubleval($money), $fix, '.', '');
        }
        else
            $money = 0.00;
        return $money;
    }

    /**
     * 查询产品列表,产品数据需要返回风险等级。风险等级关联系统参数表
     * 
     * 
    */
    public function productList()
    {
        $res = array('result'=>self::RET_SUCCESS, 'code'=>self::API_OK, 'msg'=>'OK', 'data'=>'');
        if (IS_POST){
            $MProduct = D('Admin/Product');
            $MPackage = D('Admin/ProductPackage');
            $data =  $MProduct->alias("p")
                              ->field('p.product_id,p.name as product_name,p.risk_rank,spd.detail_value as risk_char')
                              ->join("LEFT JOIN sys_param_detail spd on spd.sys_param_detail_id=p.risk_rank")
                              ->select();
            $wheres = array();
            foreach($data as &$vd){
                $wheres['product_id'] = array('eq', $vd['product_id']);
                $wheres['is_deleted'] = array('eq', 0);
                $vd['risk_rank'] = $vd['risk_char'];
                unset($vd['risk_char']);
                $vd['packages'] = $MPackage->field("package_code,package_price,package_service,name as package_name")->where( $wheres )->select();
                if ($vd['packages']){
                    foreach ($vd['packages'] as &$vp) {
                        $vp['package_price'] = $this->_uniCurrency( $vp['package_price']);
                    }
                }
            }
            $res['data'] = $data;
        }
        else{
            $res['result'] = self::RET_ERROR;
            $res['code'] = self::API_ERROR;
            $res['msg'] = $this->_E( self::API_ERROR);
        }
        return $res;
    }

    /**
     *  产品套餐详情
     * 
    */
    public function productDetail()
    {
        $res = array('result'=>self::RET_SUCCESS, 'code'=>self::API_OK, 'msg'=>'OK', 'data'=>'');
        if (IS_POST){
            $package_code = I('post.package_code', '', 'trim');
            $product_id = I('post.product_id','', 'trim');
            if (!$package_code||!$product_id){
                $res['result'] = self::RET_ERROR;
                $res['code'] = self::API_PARAM_ERROR;
                $res['msg'] = $this->_E( self::API_PARAM_ERROR );
            }
            else{
                $MPackage = D('Admin/ProductPackage');
                $MProduct = D('Admin/Product');
                $wheres = array();
                $wheres['product_id'] = array('eq', $product_id);
                $data = array();
                $data['product'] = $MProduct->alias("p")
                                            ->field('p.product_id,p.name as product_name,p.risk_rank,spd.detail_value as risk_char')
                                            ->join("LEFT JOIN sys_param_detail spd on spd.sys_param_detail_id=p.risk_rank")
                                            ->where('p.product_id='.$product_id)
                                            ->find();
                $wheres['package_code'] = array('eq', $package_code);
                $wheres['is_deleted'] = array('eq', 0);
                $data['package'] = $MPackage->field("package_code,package_price,package_service,name as package_name")
                                            ->where( $wheres )
                                            ->find();
                if ($data['package']){
                    $data['package']['package_price'] = $this->_uniCurrency( $data['package']['package_price']  );
                }
                if (!$data['product'] || !$data['package']){
                    $res['result'] = self::RET_ERROR;
                    $res['code'] = self::API_PRODUCT_NO_DATA;
                    $res['msg']  = $this->_E( self::API_PRODUCT_NO_DATA);
                }
                else{
                    $data['product']['risk_rank'] = $data['product']['risk_char'];
                    unset($data['product']['risk_char']);
                    $res['data'] = $data;
                }
            }
        }
        else{
            $res['result'] = self::RET_ERROR;
            $res['code'] = self::API_METHOD_ERROR;
            $res['msg'] = $this->_E( self::API_METHOD_ERROR);
        }
        return $res;
    }


    /**
     * 录入客户信息
     * 
    */
    public function customerAdd()
    {
        $res = array('result'=>self::RET_ERROR, 'code'=>self::API_METHOD_ERROR, 'msg'=>'OK', 'data'=>'');
        $res['msg'] = $this->_E( self::API_METHOD_ERROR );

        if (IS_POST){
            $customerInfo = $contractInfo = $payInfo = array();
            $customerInfo['customer_name'] = I('post.customer_name','','trim');
            $customerInfo['phone'] = I('post.customer_phone', '', 'trim');
            $customerInfo['weixin_id'] = I('post.customer_weixin', '', 'trim');
            $customerInfo['sex'] = I('post.customer_gender', 0, 'intval');
            $customerInfo['staff_no'] = I('post.staff_no', '', 'trim');
            $contractInfo['package'] = I('post.contract_package', '', 'trim');
            $contractInfo['product'] = I('post.contract_product', '', 'trim'); 
            $contractInfo['start_time'] = I('post.contract_start_time', '', 'trim');
            $contractInfo['end_time'] = I('post.contract_end_time', '', 'trim');
            $contractInfo['survey_code'] = I('post.survey_code', '', 'trim'); 
            $contractInfo['order_number'] = I('post.order_number', '', 'trim'); 
            $payInfo = isset($_POST['pays'])  ? (array)$_POST['pays'] : FALSE;

            #检查参数是否完整
            if (!$customerInfo['customer_name'] || !$customerInfo['phone'] || !$customerInfo['weixin_id'] || !$customerInfo['staff_no']){
                $res['code'] = self::API_CUSTOMER_PARAM_MISSING;
                $res['msg'] = $this->_E( self::API_CUSTOMER_PARAM_MISSING );
                return $res;
            }

            #检查后台员工是否存在,获取员工经理信息
            $MUser = D('Admin/User');
            $MSector = D('Admin/Sector');
            $whereu = array();
            $whereu['login_name'] = array('eq', $customerInfo['staff_no']);
            $dataUser = $MUser->where( $whereu )->find();
            if (!$dataUser){
                $res['code'] = self::API_CUSTOMER_USER_MISSING;
                $res['msg'] = $this->_E( self::API_CUSTOMER_USER_MISSING );
                return $res;
            }
            $customerInfo['sales_person'] = $dataUser['user_id'];
            $whereu = array();
            $whereu['s.sector_id'] = array('eq', $dataUser['sector_id'] );
            $dataSector = $MSector->alias("s")
                                  ->field("s.*,u.nickname as manager_name")
                                  ->join("LEFT JOIN user u on u.user_id=s.manager_id")
                                  ->where( $whereu )
                                  ->find();
            //获取部门经理
            $customerInfo['sales_manager'] = $dataSector&&isset($dataSector['manager_id']) ? $dataSector['manager_id']:0;
            $customerInfo['sales_sub_company'] = $dataSector&&isset($dataSector['parent_company']) ? $dataSector['parent_company']:0;
            $customerInfo['manager'] =  $dataSector&&isset($dataSector['manager_name']) ? $dataSector['manager_name']:'';
            $customerInfo['_data']['sales'] = $dataUser;
            $customerInfo['_data']['manager']['user_id'] = $customerInfo['sales_manager']; 
            $customerInfo['_data']['team'] = $customerInfo['sales_sub_company'];
            #检查电话号码是否正常
            if (!preg_match('/^1[34578]{1}\d{9}/', $customerInfo['phone'])){
                $res['code'] = self::API_CUSTOMER_PHONE_WRONG;
                $res['msg'] = $this->_E( self::API_CUSTOMER_PHONE_WRONG );
                return $res;
            }
            #检查合同参数是否正常,合同对应在个订单编号
            if (!$contractInfo['package'] || !$contractInfo['start_time'] || !$contractInfo['end_time'] || 
                                            !$contractInfo['survey_code'] || !$contractInfo['order_number'] ){
                $res['code'] = self::API_CUSTOMER_CONTRACT_PARAM;
                $res['msg'] = $this->_E( self::API_CUSTOMER_CONTRACT_PARAM );
                return $res;
            }
            #检查合同时间是否正常
            $tm = strtotime('-3 months');
            if (!strtotime($contractInfo['start_time']) || strtotime($contractInfo['start_time'])<$tm ){
                $res['code'] = self::API_CUSTOMER_CONTRACT_TIME;
                $res['msg'] = $this->_E( self::API_CUSTOMER_CONTRACT_TIME );
                return $res;
            }
            #检查套餐是否存在
            $MPackage = D('Admin/ProductPackage');
            $wherepk = array();
            $wherepk['pkg.package_code'] = array('eq', $contractInfo['package']);
            $dataPackage = $MPackage->alias("pkg")
                                    ->field("pkg.*,pl.default_qy_code")
                                    ->join("LEFT JOIN product_line pl on pl.product_line_code=pkg.product_line_code")
                                    ->where( $wherepk )
                                    ->find();
            if (!$dataPackage || ($dataPackage && !$dataPackage['default_qy_code'])){
                $res['code'] = self::API_CUSTOMER_PACKAGE_WRONG;
                $res['msg'] =  $this->_E( self::API_CUSTOMER_PACKAGE_WRONG );
                return $res;
            }
            #检查付款信息是否正常
            if (!$payInfo || ($payInfo&&count($payInfo)==0) || !isset($payInfo[0]['pay_time']) || !isset($payInfo[0]['pay_name']) || !isset($payInfo[0]['pay_way']) ){
                $res['code'] = self::API_CUSTOMER_PAY_WRONG;
                $res['msg'] =  $this->_E( self::API_CUSTOMER_PAY_WRONG );
                return $res;
            }
            
            #检查客户是否存在
            $MCustomerService = new CustomerService();
            $findUser = $MCustomerService->findCount($customerInfo['customer_name'], $customerInfo['manager'], 
                                                            $customerInfo['phone'],FALSE, $customerInfo['weixin_id']);
            $customer_id = 0;
            #开启数据库事务
            $MUser->startTrans();
            if ($findUser&&$findUser['data']==1&&$findUser['find']){
                $customer_id = $findUser['find']['customer_id'];
            }
            else{
                #客户不存在，注册客户信息
                $retRegister = $MCustomerService->register( $customerInfo );
                #客户服务开始时间计算,在更新合同的时候自动更新
                if ($retRegister && $retRegister['rcode']){
                    $customer_id = $retRegister['data'];
                }
                else{
                    $res['code'] = self::API_CUSTOMER_REGISTER_FAILED;
                    $res['msg'] = $this->_E( self::API_CUSTOMER_REGISTER_FAILED );
                    if (defined('APP_DEBUG')&&APP_DEBUG)
                        $res['msg'] .= '错误信息：'.$retRegister['msg'];
                    $MUser->rollback();
                    return $res;
                }
            }
            #生成合同
            $contract_mount = 0.00;
            foreach ($payInfo as $vp) {
                $contract_mount += doubleval($vp['pay_amount']);
            }
            //生成合同需要的额外信息
            $contractExt = array();
            $contractExt['survey_code'] = $contractInfo['survey_code'];
            $contractExt['product'] = $dataPackage['product_id'];
            $contractExt['sales'] = array(
                                        'user_id' => $dataUser['user_id'],
                                        'sector_id' => $dataUser['sector_id']
                                         );
            $contractExt['manager'] = array('user_id'=> $customerInfo['sales_manager']);
            $contractExt['team'] = $customerInfo['sales_sub_company'];
            #合同付款信息中，甲方信息。多次付款只允许一种付款方式
            #多笔付款一个订单的问题,订单流水,合同对应一个订单号
            $contractExt['pay']['pay_way'] = $payInfo[0]['pay_way'];//需要支付方式，用于生成合同编号
            $contractExt['order_number'] = $contractInfo['order_number'];
            $retContract  = $MCustomerService->addContract($customer_id, $contract_mount, $contractInfo['start_time'],
                                                            $contractInfo['end_time'],'', $contractExt);
            unset( $contractExt['order_number'] );
            $contract_id = 0;
            if ($retContract){
                $contract_id = $retContract;
            }
            else{
                $res['code'] = self::API_CUSTOMER_CONTRACT_FAILED;
                $res['msg'] = $this->_E( self::API_CUSTOMER_CONTRACT_FAILED );
                $MUser->rollback();
                return $res;
            }
            
            #TODO 开通订阅用户,需要传入是的那个企业号开通
            $MSubscriber = D('Admin/QySubscriber');
            $MCustomer = D('Admin/Customer');
            $dataCustomer = $MCustomer->where('customer_id='.$customer_id)->find();
            $wheresub = array();
            $wheresub['qy_subscriber_userid'] = array('eq', $dataCustomer['customer_code']);
            $wheresub['qy_code'] = array('eq', $dataPackage['default_qy_code']);
            $dataSubscriber = $MSubscriber->where( $wheresub )->find();
            $SubscriberService = new SubscriberService();

            #多个合同用户有效期的问题
            if ($dataSubscriber){
                $ret = $SubscriberService->addPackage( $dataSubscriber['qy_subscriber_id'], $dataPackage['qy_deparment_id'], $contract_id);
                if (!$ret['rcode']){
                    $res['code'] = self::API_SUBSCRIBER_UPDATE_ERROR;
                    $res['msg'] = $this->_E( self::API_SUBSCRIBER_UPDATE_ERROR );
                    $res['msg'] .= ' Error:'.$ret['msg'];
                    $MUser->rollback();
                    return $res;
                }
            }
            else{
                $ret = $SubscriberService->add( $dataCustomer['customer_code'], $dataCustomer['nickname'], $dataCustomer['phone'], $dataCustomer['weixin_id'],
                                $dataCustomer['email'], array($dataPackage['qy_deparment_id']), $dataPackage['default_qy_code'], $contract_id,$dataCustomer['sex']
                    );
                if (!$ret['rcode']){
                    $res['code'] = self::API_SUBSCRIBER_CREATE_ERROR;
                    $res['msg'] = $this->_E( self::API_SUBSCRIBER_CREATE_ERROR );
                    $MUser->rollback();
                    return $res;
                }
            }

            #注册付款信息,检查付款信息是否是线下付款，线下付款需要财务单独审核
            $payCount = count($payInfo);
            $payDown = 0;
            $payItem = array();
            foreach ($payInfo as $vpay) {
                $payItem['mount'] = $vpay['pay_amount'];
                $payItem['pay_name'] = $vpay['pay_name'];
                $payItem['pay_way'] = $vpay['pay_way'];
                $payItem['order_number'] = $vpay['pay_order'];
                $payItem['pay_time'] = $vpay['pay_time'];
                $payItem['pay_type'] = intval($vpay['pay_type']);
                $ret = $MCustomerService->addPay($customer_id, $contract_id, $vpay, $contractExt);
                if ($ret)
                    $payDown++;
            }
            
            if ( $payDown && $payDown == $payCount){
                $res['result'] = self::RET_SUCCESS;
                $res['code'] = self::API_OK;
                $res['msg'] = $this->_E( self::API_OK);
                //返回客户编码以及合同编码
                $data = array();
                $data['customer_code'] = $dataCustomer['customer_code'];
                $data['contract_code'] = D('Admin/Contract')->where('contract_id='.$contract_id)->getField('order_num');
                $res['data'] = $data;
                #添加付款信息成功，提交事务
                $MUser->commit();
               
                
            }
            else{
                $res['code'] = self::RET_ERROR;
                $res['msg'] = $this->_E( self::API_PAY_FAILED );
                #添加付款信息失败，回滚事务
                $MUser->rollback();
            }
        }
        
        return $res;
    }

    /**
     * 根据客户编码、手机号、微信号码查询客户信息
     * 
     * 
    */
    public function customerDetail()
    {
        $res = array('result'=>self::RET_ERROR, 'code'=>self::API_METHOD_ERROR, 'msg'=>'', 'data'=>'');
        $res['msg'] = $this->_E( self::API_METHOD_ERROR);
        if (IS_POST){
            $customer_code = I('post.customer_code', '', 'trim');
            $phone_number = I('post.phone_number', '', 'trim');
            $weixin_id = I('post.weixin_id'. '', 'trim');

            if (!$customer_code && !$phone_number && !$weixin_id){
                $res['code'] = self::API_PARAM_ERROR;
                $res['msg'] = $this->_E( self::API_PARAM_ERROR ); 
            } 
            else{
                $MCustomer = D('Admin/Customer');
                $wheres = array();
                $userData = false;
                if ($customer_code){
                    $wheres['c.customer_code'] = array('eq', $customer_code);
                    $userData = $MCustomer->alias("c")->where( $wheres )->find();
                }
                else{
                    if ($weixin_id){
                        $wheres['c.weixin_id'] = array('eq', $weixin_id);
                        $userData = $MCustomer->alias("c")->where( $wheres )->find();
                    }

                    if ($phone_number && !$userData){
                        $MPhoneBook = D('Admin/CustomerPhonebook');
                        $wheres = array();
                        $wheres['cpb.book_phone'] = array('eq', $phone_number);
                        $userData = $MPhoneBook->alias('cpb')
                                               ->field('c.*')
                                               ->join("left join customer c on c.customer_id=cpb.customer_id")
                                               ->where( $wheres )
                                               ->find();
                    }
                }

                if (!$userData){
                    $res['result'] = self::RET_ERROR;
                    $res['code'] = self::API_CUSTOMER_NO_DATA;
                    $res['msg'] = $this->_E( self::API_CUSTOMER_NO_DATA);
                }
                else{
                    $res['result'] = self::RET_SUCCESS;
                    $res['code'] = self::API_OK;
                    $res['msg'] = $this->_E( self::API_OK);
                    $data = array();
                    $data['customer_name'] = $userData['nickname'];
                    $data['phone'] = $userData['phone'];
                    $data['status'] = $userData['state'];
                    $data['customer_code'] = $userData['customer_code'];
                    #获取用户最新评分
                    $wheres = array();
                    $MSurvey = D('Admin/CustomerSurvey');
                    $data['survey_rank'] = 'B';
                    $wheres['customer_id'] = array('eq', $userData['customer_id']);
                    $rank = $MSurvey->where( $wheres )->order("create_time desc")->getField('rank_level');
                    if ($rank)
                        $data['survey_rank'] = $rank;
                    $res['data'] = $data;
                }
            }
        }
        return $res;
    }

    /**
     * 获取付款列表
     * 
     * 
    */
    public function payList()
    {
        $res = array('result'=>self::RET_ERROR, 'code'=>self::API_METHOD_ERROR, 'msg'=>'', 'data'=>'');
        $res['msg'] = $this->_E( self::API_METHOD_ERROR);
        if (IS_GET){
            $MParamDetail = D('Admin/SysParamDetail');
            $wheres = array();
            $wheres['sp.key_name'] = array('eq', 'PAY_WAY');
            $_data = $MParamDetail->alias('spd')
                                 ->field('spd.detail_name,detail_value')
                                 ->join("LEFT JOIN sys_param sp on sp.sys_param_id=spd.sys_param_id")
                                 ->where( $wheres )
                                 ->select();     
            if ($_data){
                $res['result'] = self::RET_SUCCESS;
                $res['code'] = self::API_OK;
                $res['msg'] = $this->_E( self::API_OK );
                $data = array();
                foreach($_data as $vd){
                    $item = array();
                    $arrItem = explode('|', $vd['detail_value']);
                    if ($arrItem&&3==count($arrItem)){
                        //暂时只允许天津分公司打款,接口中的付款方式都是正在使用中
                        if ('北京和众汇富咨询有限公司天津分公司' == $arrItem[0]){
                            $item['company_name'] = $arrItem[0];
                            $item['bank_account'] = $arrItem[1];
                            $item['bank_address'] = $arrItem[2];
                            $item['short_name'] = $vd['detail_name'];
                            $item['in_use'] = 1;
                            $data[] = $item;
                        }
                    }
                }
                $res['data'] = $data;
            }
            else{
                $res['code'] = self::API_PAY_ERROR;
                $res['msg'] = $this->_E( self::API_PAY_ERROR ); 
            }
        }
        return $res;
    }

    /**
     * 发起电子合同
     * 
     * 
    */
    public function econtractSign()
    {
        $res = array('result'=>self::RET_ERROR, 'code'=>self::API_METHOD_ERROR, 'msg'=>'', 'data'=>'');
        $res['msg'] = $this->_E( self::API_METHOD_ERROR);
        if (IS_POST){
            $contract_code = I('post.contract_code', '', 'trim');
            $customer_code = I('post.customer_code', '', 'trim');
            $callback = I('post.callback', '', 'trim');
            $reg_http = '/\b(([\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)))/i';
            if (!$contract_code || !$customer_code){
                $res['code'] = self::API_ECONTRACT_PARAM_ERROR;
                $res['msg'] = $this->_E( self::API_ECONTRACT_CONTRACT_ERROR);
            }
            else if($callback&&!preg_match($reg_http, $callback)){
                $res['code'] = self::API_ECONTRACT_URL_ERROR;
                $res['msg'] = $this->_E( self::API_ECONTRACT_URL_ERROR);
            }
            else{
                $wheres = $wherec = array();
                $MCustomer = D('Admin/Customer');
                $wheres['customer_code'] = array('eq', $customer_code);
                $MContract = D('Admin/Contract');
                $wherec['order_num'] = array('eq', $contract_code);
                $dataCustomer = $MCustomer->where( $wheres )->find();
                $dataContract = $MContract->where( $wherec )->find();
                if (!$dataCustomer){
                    $res['code'] = self::API_ECONTRACT_CUSTOMER_ERROR;
                    $res['msg'] = $this->_E( self::API_ECONTRACT_CUSTOMER_ERROR);
                }
                else if (!$dataContract){
                    $res['code'] = self::API_ECONTRACT_CONTRACT_ERROR;
                    $res['msg'] = $this->_E( self::API_ECONTRACT_CONTRACT_ERROR);
                }
                else{
                    $MEcontract = D('Admin/Econtract', 'Service'); 
                    #发起电子合同填充回调地址
                    $signData = $MEcontract->post( $dataContract['contract_id'], $callback);
                    if ($signData&&$signData['rcode']){
                        $res['result'] = self::RET_SUCCESS;
                        $res['code'] = self::API_OK;
                        $res['msg'] = $this->_E( self::API_OK );
                        $res['data'] = array();
                        $res['data']['sign_url'] = $signData['data']['sign_url'];
                        $res['data']['expires']  = 7200;//超时默认将2个小时
                    }
                    else{
                        $res['code'] = self::API_ECONTRACT_API_ERROR;
                        $res['msg'] = $signData['msg']; 
                    }
                }
            }
        }
        
        return $res;
    }

    /**
     * 根据自助服务系统中订单编码查询合同信息
     * 
     * 
    */
    public function econtractDetailByOrder()
    {
        $res = array('result'=>self::RET_ERROR, 'code'=>self::API_METHOD_ERROR, 'msg'=>'OK', 'data'=>'');
        $res['msg'] = $this->_E( self::API_METHOD_ERROR );
        if (IS_POST){
            $order_number = I('post.order_number', false, 'trim');
            if (!$order_number){
                $res['code'] = self::API_PARAM_ERROR;
                $res['msg'] = $this->_E( self::API_PARAM_ERROR);
            }
            else{
                $wheres = array();
                $MContract = D('Admin/Contract');
                //付款表增加order_number 字段,记录自助服务订单
                $wheres['zizhu_pay_order'] = array('eq', $order_number);
                $data = $MContract->field("order_num as contract_number,state as status,backcontract as view_url")
                             ->where($wheres)
                             ->find();
                if (!$data){ //查询失败
                    $res['code'] = self::API_ECONTRACT_DETAIL_ERROR;
                    $res['msg'] = $this->_E( self::API_ECONTRACT_DETAIL_ERROR );
                }
                else{
                    $res['result'] = self::RET_SUCCESS;
                    $res['code'] = self::API_OK;
                    $res['msg'] = $this->_E(self::API_OK);
                    $res['data'] = $data;
                }
            }
        }
        
        return $res;
    }


    /**
     * 读取问卷信息 
     * 
    */
    public function surveyRead()
    {
        $res = array('result'=>self::RET_ERROR, 'code'=>self::API_METHOD_ERROR, 'msg'=>'OK', 'data'=>'');
        $res['msg'] = $this->_E( self::API_METHOD_ERROR );
        if (IS_POST){
            $MService = new EcontractService();
            $survey_code = I('post.survey_code','', 'trim');
            $phone_number = I('post.phone_number','', 'trim');
            $ret = $MService->surveyRead($survey_code, $phone_number);
            if ($ret['rcode']){
                $res['result'] = self::RET_SUCCESS;
                $res['code'] = self::API_OK;
                $res['msg'] = $this->_E(self::API_OK);
                $surveyData = array();
                $item = array();

                foreach ($ret['data'] as $vd) {
                    $item['survey_code'] = $vd['survey_code'];
                    $item['score'] = intval($vd['survey_score']);
                    $item['rank'] = $vd['rank'];
                    $item['rankTitle'] = $vd['rankTitle'];
                    $item['time'] = $vd['create_time'];
                    $item['status'] = $vd['status'];
                    $surveyData[] = $item;
                }
                $res['data'] = $surveyData;
            }
            else{
                $res['code'] = self::API_ERROR;
                $res['msg'] = $ret['msg'];
            }
        }
        
        return $res;
    }

}